import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Лист Стан 5000'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        product_up = None
        try:
            product = row["Первичный продукт"]
            bz_sign = consolidator.scalar_in_guid("Продукт по НТД",f"`НТД качества (прокат) <Производство>`=='{row['НТД качества (прокат) <Производство>']}'","Доп признак")
            steel_mark = row["Марка стали <Производство>"]
            width = row["Ширина листа (штрипса), мм <Производство>"]
            thickness=row["Толщина, мм <Производство>"]
            steel_mark_1_letter = steel_mark[:1]
            strength = row["Класс прочности <Производство>"]
            if steel_mark_1_letter in ["К","Х","K","X"]: strength=steel_mark
            elif steel_mark_1_letter not in ["К","Х","K","X"]: strength=pd.NA
            if pd.isna(strength):
                strength=consolidator.strength_by_steel(steel_mark)
            strength_1 = consolidator.strength_mapping(strength,steel_mark)
            strength_led = consolidator.strength_led(strength_1[0])
            if strength_led=="К0": strength_led="К52"
            gmsps = consolidator.get_gmsps(steel_mark,product)
            diametr_=0
            if width==1500 or width==2000: diametr_=0
            q1020_1 = (width - 5) * (1 - 0.4 / 100) * (1 + 1.1 / 100) / 3.1416 + thickness
            q1420_1 = (width - 5) * (1 - 0 / 100) * (1 + 0.6 / 100) / 3.1416 + thickness
            d1020 = consolidator.nearest_in_guid("Диаметры ТБД","`Диаметры`>0","Диаметры",q1020_1,"Диаметры")
            d1420 = consolidator.nearest_in_guid("Диаметры ТБД","`Диаметры`>0","Диаметры",q1420_1,"Диаметры")            
            delta_abs_1020=abs(q1020_1-d1020)
            delta_abs_1420=abs(q1420_1-d1420)   
            if delta_abs_1020<delta_abs_1420 : diametr_=d1020
            else : diametr_=d1420
            diametr = str(diametr_).replace(".0","")
            
            thickness_range=None
            if product=="ЛИСТ ТРБ":
                thickness_range = consolidator.scalar_in_guid("Параметры по Продукту Прокат",
                # f"`Производство`=='Лист Стан 5000' and `Продукт`=='{product}' and `Доп параметр2`=='{strength_led}' and `Доп параметр3`=='ШВ1' and `Мин`<={thickness}<=`Макс`",
                f"`Производство`=='Лист Стан 5000' and `Продукт`=='{product}' and `Доп параметр2`=='{strength_led}' and `Доп параметр3`=='ШВ1' and `Доп параметр1`=='{diametr}'",
                "Диапазон")
                product_up=f"{product} Д{diametr} {thickness_range} ШВ1 {strength_led}"
            elif product=="ЛИСТ Р":
                if str(bz_sign)=="БЗ":
                    thickness_range = consolidator.scalar_in_guid("Параметры по Продукту Прокат",
                    f"`Производство`=='Лист Стан 5000' and `Продукт`=='{product}' and `Доп параметр1`=='БЗ' and `Мин`<={thickness}<=`Макс`",
                    "Диапазон")
                    product_up=f"{product} {thickness_range} БЗ"
                else:
                    thickness_range = consolidator.scalar_in_guid("Параметры по Продукту Прокат",
                    f"`Производство`=='Лист Стан 5000' and `Продукт`=='{product}' and `Доп параметр1`=='{gmsps}' and `Мин`<={thickness}<=`Макс`",
                    "Диапазон")
                    product_up = f"{product} {thickness_range} {gmsps}"
            
            print(f"{row['ID в SAP ERP VMZ']} - {product} - {strength_led} - {gmsps} - {diametr_}")
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__sheet_5k__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

